//评估记录
import * as React from 'react';
import {
  TreeSelect,
  Modal,
  Row,
  Col,
  DatePicker,
  Menu,
  Steps,
  Dropdown,
  Icon,
  Input,
  Table,
  Button,
  Form,
  message,
  InputNumber,
  notification
} from 'antd';
import router from 'umi/router';
import axios from 'axios';
import Api from '../../services/apis';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { formatTreeData } from '../../components/commonAips';
import { connect } from 'dva';
const confirm = Modal.confirm;
const FormItem = Form.Item;


@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))

class givePermission extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: '',
      name: '',
      _name: '',
      _number: '',
      modalVisible: false,
      modifyVisible: false,
      newNumber: '',
      newName: '',
      newPassword: '',
      samePassword: '',
      newPhone: '',
      newDepartment: '',
      newArea: '',
      selectedArr: [],
      selectedId: [],
      tableData: [],
    };
  }

  componentWillMount() {
    //获取表格数据
    this.sendData();
  }

  resetForm() {
    this.setState({
      number: '',
      name: '',
    });
  }

  sendData() {
    const that = this;
    let param = new URLSearchParams();
    param.append('functionName', this.state.number);
    param.append('userId', this.props.location.query ? this.props.location.query.id : '');

    axios
      .post(Api.umGetFunListByUser, {
        functionName: this.state.number,
        userId: this.props.location.query ? this.props.location.query.id : '',
      })
      .then(function(resp) {
        const {data} = resp;
        if (data) {
          let tmp = [];
          let selectedArr = [];
          for (let i = 0, len = data.length; i < len; i++) {
            tmp.push({
              key: i + 1,
              functionName: data[i].functionName ? data[i].functionName : '-',
              functionCode: data[i].functionCode ? data[i].functionCode : '-',
              functionDesc: data[i].functionDesc ? data[i].functionDesc : '-',
              functionId: data[i].functionId ? data[i].functionId : '-',
              modifyDateStr: data[i].modifyDateStr ? data[i].modifyDateStr : '-',
            });
            if (data[i].roleHaveFunction) {
              selectedArr.push(i + 1);
            }
          }
          that.setState({
            tableData: tmp,
            totalSize: data.length,
            selectedArr: selectedArr,
            userId: that.props.location.query ? that.props.location.query.id : '',
          });
        }
      });
  }

  changeNumber = e => {
    this.setState({ number: e.target.value });
  };

  changeUser = id => {
    this.setState({ modifyVisible: true, modifyId: id });
  };

  setModalVisible = () => {
    let that = this;
    if(this.state.selectedId.length!=0){
    axios
      .post(Api.umGetFunListByUser, {
        funArray: this.state.selectedId.join(','),
        userId: this.state.userId,
      })
      .then(function(resp) {
        const {data} = resp;
        if (data && data.code == 1) {
          Modal.info({
            title: '信息',
            content: '授权成功',
            onOk() {},
          });
        } else {
          Modal.info({
            title: '信息',
            content: data.msg,
            onOk() {},
          });
        }
      });
    }else{
      notification.destroy();
      notification['warning']({message:'请选择列表项后进行操作！'})
    }
  };

  addNumber = e => {
    this.setState({ newNumber: e.target.value });
  };

  closeIframe = () => {
    let aaa = {
      pathname: '/fe/systemManagement/userEmpowerment',
      query: {
        number: this.state._number,
        name: this.state._name,
      },
    };
    router.push(aaa);
  };

  changeSelected = (selectedRowKeys, selectedRows) => {
    let selectedId = [];
    selectedRows &&
      selectedRows.map((item, index) => {
        selectedId.push(item.functionId);
      });

    this.setState({ selectedArr: selectedRowKeys, selectedId: selectedId });
  };

  render() {
    let that = this;
    //表头
    const columns = [
      {
        title: '权限名称',
        dataIndex: 'functionName',
        key: 'functionName',
      },
      {
        title: '管理编码',
        dataIndex: 'functionCode',
        key: 'functionCode',
      },
      {
        title: '描述',
        dataIndex: 'functionDesc',
        key: 'functionDesc',
      },
      {
        title: '修改日期',
        dataIndex: 'modifyDateStr',
        key: 'modifyDateStr',
      },
    ];

    const rowSelection = {
      selectedRowKeys: this.state.selectedArr,
      onChange: (selectedRowKeys, selectedRows) => {
        that.changeSelected(selectedRowKeys, selectedRows);
      },
    };
    const {
      currentUserLoading,
    } = this.props;

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
      <div className="mainContainer">
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>用户赋予权限</p>
              <p>USER ENDOW PERMISSION</p>
            </div>
          </div>
          <div className='clearfix'>
            <Button type='primary' className='pull-right' onClick={this.closeIframe}>返回</Button>
          </div>
        <div className='mrb15'>
          <Form layout="inline" align='center'>
              <FormItem>
                <span className="erlabel">权限名称：</span>
                <Input
                  value={this.state.number}
                  data-inp="zdbh"
                  onChange={this.changeNumber.bind(this)}
                  placeholder="请输入"
                />
              </FormItem>
              <Row gutter={24} style={{ textAlign: 'center'}}>
                <Button icon='search' type="primary" className="evfilterbtn" onClick={this.sendData.bind(this)}>
                  查询
                </Button>
                  &emsp;
                <Button
                  onClick={this.resetForm.bind(this)}
                  type="primary"
                  htmlType="reset"
                  className="evfilterbtn" icon="reload"
                >
                  重置
                </Button>
                  &emsp;
                <Button
                  type="primary"
                  onClick={() => this.setModalVisible(true)}
                  icon="plus-circle"
                >
                  赋权
                </Button>
            </Row>
        </Form>
        </div>

          <Row className="choicedBox">
            <Table
              rowSelection={rowSelection}
              bordered={true}
              scroll={{x:true}}
              align={'center'}
              columns={columns}
              dataSource={this.state.tableData}
              pagination={{
                defaultPageSize: 5,
                total: that.state.totalSize,
                showTotal: total => `共 ${total} 项`
              }}
            />
          </Row>
      </div>
      </PageHeaderWrapper>
    );
  }
}

export default givePermission;
